﻿using UnityEngine;
using System.Collections;

[System.Serializable]
public struct xy {
	public int x, y;
	xy(int a, int b) {
		x = a;
		y = b;
	}
}

public struct xywh {
	public int x, y, w, h;
	xywh(xy a, xy b) {
		x = a.x;		y = a.y;
		w = b.x;		h = b.y;
	}
}

public interface ICanSwim {
	bool wantsToGoBackInThePool();
	void getInThePool();
	void getOutOfThePool();
}

public class Pool<T> where T : ICanSwim, new() {
	public T[] array;
	public int size;
	public int maxlen;
	public void init(int _maxlen) {
		maxlen = _maxlen;
		array = new T[maxlen];
		for (int i = 0; i < maxlen; i++) {
			array [i] = new T ();
		}
	}
	public T this[int i] {get{return array[i];}}
	public T get() {
		if (size < maxlen) size++;
		int j = size - 1;
		array[j].getOutOfThePool ();
		return array[j];
	}
	public void remove(ref int i) {
		int j = size-1;
		T t = array[i];
		array[i] = array[j];
		array[j] = t;
		array[j].getInThePool ();
		size--;
		i--;
	}
	public void poolCleaner() {
		for (int i = 0; i < size; i++) {
			if (array[i].wantsToGoBackInThePool()) {
				remove (ref i);
			}
		}
	}
	public void poolParty() {
		for (int i = 0; i < size; i++) {
			array [i].getInThePool ();
		}
	}
}

public static class Poolx {
	public static void defrag(ref ICanSwim[] pool, ref int size) {
		for (int i = 0; i < size; i++) {
			if (pool[i].wantsToGoBackInThePool()) {
				int j = size-1;
				pool[i] = pool[j];
				pool[j].getInThePool();
				size--;
			}
		}
	}

	public static Object fish(ref ICanSwim[] pool, ref int size) {
		if (size >= pool.Length) return null;
		int j = size;
		size++;
		pool [j].getOutOfThePool ();
		return (Object) pool[j];
	}

}

